package com.itfreer.print.service.toPdf;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.print.toPdf.HtmlToPdf;
import com.itfreer.utils.json.JsonUtils;

/**
 * 发布rest调用服务
 */
@Component
@Path("/print/")
public class HtmlToPdfRestService {

	@Autowired
	private HtmlToPdf htmlToPdf;
	
	/**
	 * 基于模板输出excel文件
	 * 
	 * @param template
	 *            模板文件
	 * @param data
	 *            模板数据
	 */
	@SuppressWarnings("rawtypes")
	@POST
	@Path("/HtmlToPdf")
	public Response toPdf(@FormParam("template") String template, 
			@FormParam("data") String dataString,
			@FormParam("filename") String filename) throws Exception {
		HashMap data = JsonUtils.toBean(dataString, HashMap.class);
		// 读取目标文件，通过response将目标文件写到客户端
		ByteArrayOutputStream outFile = new ByteArrayOutputStream();
		htmlToPdf.toPdf(template, data, outFile);
		StreamingOutput stream = new StreamingOutput() {
			@Override
			public void write(OutputStream output) throws IOException, WebApplicationException {
				try {
					output.write(outFile.toByteArray());
	            } catch (Exception e) {
	                throw new WebApplicationException(e);
	            }
			}
	    };
	    outFile.close();

	    return Response.ok(stream)
	    		.header("Content-Disposition","inline; filename =" + new String(filename.getBytes("utf-8"), "ISO-8859-1"))
	    		.header("Content-Type", "application/pdf")
	    		.header("Cache-Control", "no-cache").build();
	}
}
